package org.thaonv;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class MultiThread
 */
@WebServlet("/MultiThread")
public class MultiThread extends HttpServlet  {
	private static final long serialVersionUID = 1L;
	ExecutorService executor = Executors.newFixedThreadPool(4);
	
       
    public MultiThread() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */ 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String user=request.getParameter("username");
		System.out.println(user);
	
		Thread worker = new WorkerThread(user);
		executor.execute(worker);
		try {
			worker.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Finished all threads");
		response.sendRedirect("welcome.html");
		
		
//			Thread worker = new AccessDB(user);
//			executor.execute(worker);
////			executor.shutdown();  
//			try {
//				while (!worker.isInterrupted()) {
//					response.sendRedirect("welcome.html");
//					System.out.println("Success");
//				}
//				
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		
	}


}
